package com.dhcc.cdbp.solrj;

import java.io.IOException;
import java.util.Date;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;

/**
 * Hello world!
 *
 */
public class App {
	public static void main(String[] args) throws SolrServerException,
			IOException {
		System.out.println("xxxxx");
		HttpSolrServer server = new HttpSolrServer(
				"http://localhost:8080/solr/core_c");
		SolrInputDocument document = new SolrInputDocument();
		document.addField("id", "552199");
		document.addField("name", "Gouda cheese wheel");
		document.addField("orgCode", "donghua");
		document.addField("createTime", new Date());
		document.addField("xx", new Date());
		UpdateResponse response = server.add(document);
		// 最后记得 commit 使索引生效</div>
		server.commit();
	}

	private static final String urlString = "http://localhost:8080/solr/core_c";

	/**
	 * Indexing Documents
	 * 
	 * @throws SolrServerException
	 * @throws IOException
	 */
	@Test
	public void testSolr() throws SolrServerException, IOException {
		SolrClient solr = new HttpSolrClient(urlString);
		SolrInputDocument document = new SolrInputDocument();
		document.addField("id", "test_1");
		document.addField("name", "Gouda cheese wheel");
		document.addField("orgCode", "donghua");
		document.addField("createTime", new Date());
		UpdateResponse response = solr.add(document);
		solr.commit();
	}

	@Test
	public void testSolrJSearcher() throws SolrServerException, IOException {
		SolrClient solr = new HttpSolrClient(urlString);
		SolrQuery query = new SolrQuery();
		query.setQuery("test_1");
		query.addFilterQuery("id:test_1", "name:Gouda cheese wheel");
		query.setFields("id", "name", "orgCode", "createTime");
		query.setStart(0);
		// query.set("defType", "edismax");
		QueryResponse response = solr.query(query);
		SolrDocumentList results = response.getResults();

		for (int i = 0; i < results.size(); i++) {
			System.out.println(results.get(i));
		}
	}

	@Test public static void solrOrder() throws SolrServerException, IOException {
		SolrClient solr = new HttpSolrClient(urlString);
		System.out.println("yy");
		SolrQuery query = new SolrQuery();
		query.setQuery("*:*");
		// query.addSort("id", SolrQuery.ORDER.asc);
		QueryResponse response = solr.query(query);
		SolrDocumentList results = response.getResults();

		for (int i = 0; i < results.size(); i++) {
			System.out.println(results.get(i));
		}
	}
}
